from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                              QRadioButton, QSpinBox, QPushButton, QGroupBox,
                              QGridLayout, QButtonGroup, QFrame)
from PySide6.QtCore import Qt, Signal, QTimer
from PySide6.QtGui import QFont, QCursor
import pyautogui

class DetectionAreaDialog(QDialog):
    """检测区域设置对话框"""
    
    def __init__(self, trigger_item, parent=None):
        super().__init__(parent)
        self.trigger_item = trigger_item
        self.setWindowTitle("检测区域设置")
        self.setFixedSize(500, 400)
        self.setup_ui()
        self.load_settings()
        
    def setup_ui(self):
        layout = QVBoxLayout(self)
        
        # 标题
        title_label = QLabel("颜色检测区域设置")
        title_font = QFont()
        title_font.setPointSize(14)
        title_font.setBold(True)
        title_label.setFont(title_font)
        title_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(title_label)
        
        # 说明文字
        info_label = QLabel("选择颜色检测的位置，避免检测到游戏准星等固定元素")
        info_label.setStyleSheet("color: gray; margin: 10px;")
        info_label.setWordWrap(True)
        layout.addWidget(info_label)
        
        # 检测模式选择
        mode_group = QGroupBox("检测模式")
        mode_layout = QVBoxLayout(mode_group)
        
        self.mode_group = QButtonGroup()
        
        # 屏幕中心模式
        self.center_radio = QRadioButton("屏幕中心")
        self.center_radio.setToolTip("检测屏幕正中心的颜色（可能会检测到准星）")
        mode_layout.addWidget(self.center_radio)
        self.mode_group.addButton(self.center_radio, 0)
        
        # 鼠标位置模式
        self.mouse_radio = QRadioButton("鼠标位置")
        self.mouse_radio.setToolTip("检测当前鼠标指针位置的颜色")
        mode_layout.addWidget(self.mouse_radio)
        self.mode_group.addButton(self.mouse_radio, 1)
        
        # 自定义位置模式
        self.custom_radio = QRadioButton("自定义位置")
        self.custom_radio.setToolTip("手动设置检测位置的坐标")
        mode_layout.addWidget(self.custom_radio)
        self.mode_group.addButton(self.custom_radio, 2)
        
        layout.addWidget(mode_group)
        
        # 自定义坐标设置
        coord_group = QGroupBox("自定义坐标")
        coord_layout = QGridLayout(coord_group)
        
        coord_layout.addWidget(QLabel("X坐标:"), 0, 0)
        self.x_spin = QSpinBox()
        self.x_spin.setRange(0, 9999)
        self.x_spin.setValue(960)  # 默认屏幕中心
        coord_layout.addWidget(self.x_spin, 0, 1)
        
        coord_layout.addWidget(QLabel("Y坐标:"), 1, 0)
        self.y_spin = QSpinBox()
        self.y_spin.setRange(0, 9999)
        self.y_spin.setValue(540)  # 默认屏幕中心
        coord_layout.addWidget(self.y_spin, 1, 1)
        
        # 获取当前鼠标位置按钮
        self.get_mouse_btn = QPushButton("获取当前鼠标位置")
        self.get_mouse_btn.clicked.connect(self.get_current_mouse_position)
        coord_layout.addWidget(self.get_mouse_btn, 2, 0, 1, 2)
        
        layout.addWidget(coord_group)
        
        # 检测区域大小
        area_group = QGroupBox("检测区域大小")
        area_layout = QHBoxLayout(area_group)
        
        area_layout.addWidget(QLabel("区域大小:"))
        self.area_spin = QSpinBox()
        self.area_spin.setRange(1, 21)
        self.area_spin.setSingleStep(2)  # 只允许奇数
        self.area_spin.setValue(1)
        self.area_spin.setToolTip("1=单点检测, 3=3x3区域, 5=5x5区域等")
        area_layout.addWidget(self.area_spin)
        
        area_layout.addWidget(QLabel("像素"))
        area_layout.addStretch()
        
        # 区域说明
        area_info = QLabel("1=单点 3=3x3区域 5=5x5区域 (奇数)")
        area_info.setStyleSheet("color: gray; font-size: 10px;")
        area_layout.addWidget(area_info)
        
        layout.addWidget(area_group)
        
        # 实时预览
        preview_group = QGroupBox("实时预览")
        preview_layout = QVBoxLayout(preview_group)
        
        self.preview_label = QLabel("当前检测位置: 未设置")
        preview_layout.addWidget(self.preview_label)
        
        self.preview_btn = QPushButton("开始实时预览")
        self.preview_btn.clicked.connect(self.toggle_preview)
        preview_layout.addWidget(self.preview_btn)
        
        layout.addWidget(preview_group)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        
        self.ok_btn = QPushButton("确定")
        self.ok_btn.clicked.connect(self.accept)
        button_layout.addWidget(self.ok_btn)
        
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_btn)
        
        layout.addLayout(button_layout)
        
        # 连接信号
        self.mode_group.buttonClicked.connect(self.on_mode_changed)
        self.custom_radio.toggled.connect(coord_group.setEnabled)
        
        # 预览定时器
        self.preview_timer = QTimer()
        self.preview_timer.timeout.connect(self.update_preview)
        self.is_previewing = False
        
    def load_settings(self):
        """加载当前设置"""
        # 设置检测模式
        if self.trigger_item.detection_mode == "center":
            self.center_radio.setChecked(True)
        elif self.trigger_item.detection_mode == "mouse":
            self.mouse_radio.setChecked(True)
        else:
            self.custom_radio.setChecked(True)
            
        # 设置自定义坐标
        if self.trigger_item.detection_x is not None:
            self.x_spin.setValue(self.trigger_item.detection_x)
        if self.trigger_item.detection_y is not None:
            self.y_spin.setValue(self.trigger_item.detection_y)
            
        # 设置区域大小
        self.area_spin.setValue(self.trigger_item.detection_area_size)
        
        # 更新UI状态
        self.on_mode_changed()
        
    def on_mode_changed(self):
        """检测模式改变时的处理"""
        is_custom = self.custom_radio.isChecked()
        self.x_spin.setEnabled(is_custom)
        self.y_spin.setEnabled(is_custom)
        self.get_mouse_btn.setEnabled(is_custom)
        
    def get_current_mouse_position(self):
        """获取当前鼠标位置"""
        try:
            x, y = pyautogui.position()
            self.x_spin.setValue(x)
            self.y_spin.setValue(y)
            print(f"获取鼠标位置: ({x}, {y})")
        except Exception as e:
            print(f"获取鼠标位置失败: {e}")
            
    def toggle_preview(self):
        """切换实时预览"""
        if self.is_previewing:
            self.stop_preview()
        else:
            self.start_preview()
            
    def start_preview(self):
        """开始实时预览"""
        self.is_previewing = True
        self.preview_btn.setText("停止预览")
        self.preview_timer.start(500)  # 每500ms更新一次
        print("开始实时预览检测位置")
        
    def stop_preview(self):
        """停止实时预览"""
        self.is_previewing = False
        self.preview_btn.setText("开始实时预览")
        self.preview_timer.stop()
        self.preview_label.setText("当前检测位置: 预览已停止")
        print("停止实时预览")
        
    def update_preview(self):
        """更新预览信息"""
        try:
            x, y = self.get_detection_position()
            if x is not None and y is not None:
                # 获取该位置的颜色
                from PIL import ImageGrab
                screenshot = ImageGrab.grab()
                color = screenshot.getpixel((x, y))
                
                self.preview_label.setText(
                    f"检测位置: ({x}, {y}) | "
                    f"颜色: RGB({color[0]}, {color[1]}, {color[2]}) | "
                    f"十六进制: #{color[0]:02x}{color[1]:02x}{color[2]:02x}"
                )
            else:
                self.preview_label.setText("检测位置: 无效坐标")
                
        except Exception as e:
            self.preview_label.setText(f"预览错误: {e}")
            
    def get_detection_position(self):
        """获取当前设置的检测位置"""
        if self.center_radio.isChecked():
            # 屏幕中心
            screen_width, screen_height = pyautogui.size()
            return screen_width // 2, screen_height // 2
        elif self.mouse_radio.isChecked():
            # 鼠标位置
            return pyautogui.position()
        else:
            # 自定义位置
            return self.x_spin.value(), self.y_spin.value()
            
    def get_settings(self):
        """获取设置结果"""
        settings = {}
        
        if self.center_radio.isChecked():
            settings['detection_mode'] = "center"
        elif self.mouse_radio.isChecked():
            settings['detection_mode'] = "mouse"
        else:
            settings['detection_mode'] = "custom"
            
        settings['detection_x'] = self.x_spin.value()
        settings['detection_y'] = self.y_spin.value()
        settings['detection_area_size'] = self.area_spin.value()
        
        return settings
        
    def accept(self):
        """确定按钮处理"""
        self.stop_preview()
        
        # 应用设置
        settings = self.get_settings()
        self.trigger_item.detection_mode = settings['detection_mode']
        self.trigger_item.detection_x = settings['detection_x']
        self.trigger_item.detection_y = settings['detection_y']
        self.trigger_item.detection_area_size = settings['detection_area_size']
        
        print(f"检测区域设置已保存: {settings}")
        super().accept()
        
    def reject(self):
        """取消按钮处理"""
        self.stop_preview()
        super().reject()
        
    def closeEvent(self, event):
        """窗口关闭时清理"""
        self.stop_preview()
        super().closeEvent(event)
